package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.common.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class AliYxeOrderCheckTask {

    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;

    private Log logger = Log.get();


    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    @Scheduled(fixedRate = 5000)
    public void checkOrder() throws Exception {
//        logger.info("YXE订单查询..");
        Calendar c = Calendar.getInstance();

        TOrderInfo queryOrder = new TOrderInfo();
        queryOrder.setChannelType("alipay");
        queryOrder.setChannel("alipay_yxe_h5");
        queryOrder.setStatus(1);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoList(queryOrder);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        Date startTime = DateUtils.getStartOfDay(new Date());
        Date endTime = DateUtils.getEndOfDay(new Date());
        String startTimeStr = sdf.format(startTime);
        String endTimeStr = sdf.format(endTime);
        for (TOrderInfo orderInfo : orderInfos) {
            if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                continue;
            }
            TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            String url = "https://longpay.xddshare.com/ysepay/account-book/api/search/merchant/order";
            String cookieStr = orderInfo.getQrcodeTxt();
            JSONObject cookieObj = JSONObject.parseObject(cookieStr);
            String merchantCode = cookieObj.getString("sellerId");
            String token = cookieObj.getString("token");

            JSONObject queryObj = new JSONObject();
            queryObj.put("mercId", merchantCode);
            queryObj.put("pageSize", 20);
            queryObj.put("startTime", startTimeStr);
            queryObj.put("pageIndex", "0");
            queryObj.put("endTime", endTimeStr);
            JSONArray orderStatusListObj = new JSONArray();
            orderStatusListObj.add("TRADE_SUCCESS");
            queryObj.put("orderStatusList",orderStatusListObj);
            JSONArray transTypeListObj = new JSONArray();
            transTypeListObj.add("ZFB");
            queryObj.put("transTypeList",transTypeListObj);

            HashMap<String, String> headerMap = new HashMap();
            headerMap.put("cookie", "syPaySessionId="+token);
            headerMap.put("Longpay-Token", token);
            headerMap.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/20) uni-app");

//            logger.info("yxe订单查询请求：" + queryObj.toJSONString());
            String httpResponseStr = HttpUtils.sendJsonMessage(url, headerMap, queryObj.toJSONString());
            JSONObject resultObj = JSONObject.parseObject(httpResponseStr);
//            logger.info("yxe订单查询.." + resultObj);
            int resultCode = resultObj.getInteger("code");
            if (resultCode == 0) {
                JSONArray recordList = resultObj.getJSONObject("data").getJSONArray("details");
                for (int i = 0; i < recordList.size(); i++) {
                    JSONObject recordObj = recordList.getJSONObject(i);
                    if (recordObj.getString("transType").equals("ZFB") && recordObj.getString("orderStatus").equals("TRADE_SUCCESS") && Float.valueOf(MoneyUtil.fenToYuan(orderInfo.getMoney() + "")).equals(recordObj.getFloatValue("totalAmount"))) {
                        if (orderInfo.getPay3rdOrderNo().equals(recordObj.getString("tradeNo"))) {//成功订单
                            logger.info("YXE订单查询.." + recordObj);
                            MsgPayResult msgPayResult = new MsgPayResult();
                            msgPayResult.setChannel(orderInfo.getChannel());
                            msgPayResult.setTradeNo(orderInfo.getId().toString());
                            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                            msgPayResult.setOrderId(recordObj.getString("outTradeNo"));
                            msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                            msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                            msgPayResult.setBillTime(recordObj.getString("paySuccessTime"));
                            msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(recordObj));
                            chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                            chargeService.notifyUserPaySucc(orderInfo.getId());

                            logger.info("YXE订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney());
                            //查询是否有待结算金额
                            url ="https://longpay.xddshare.com/ysepay/qrcodepay/capital/merchantBalanceSearch";
                            JSONObject djsQry = new JSONObject();
                            djsQry.put("merchantNo",merchantCode);
                            String djsStr = HttpUtils.sendJsonMessage(url, headerMap, djsQry.toJSONString());
                            logger.info("YXE查询是否有冻结:" +djsStr);
                            JSONObject djsObj = JSONObject.parseObject(djsStr);
                            JSONArray accountDetails = djsObj.getJSONObject("data").getJSONArray("account_detail");
                            for (int k=0;k<accountDetails.size();k++){
                                JSONObject jsonObject = accountDetails.getJSONObject(k);
                                if(jsonObject.getString("account_type").equalsIgnoreCase("待结算账户")){
                                    if(jsonObject.getFloatValue("account_amount")>300){
                                        logger.info("*************************************YXE订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney()+"未到账！！！！");
                                        userRecipientInfo.setAvailable(0);
                                        userRecipientInfo.setChannelDisabled(1);
                                        userRecipientInfo.setDisabledInfo("YXE订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney()+"未到账");
                                        userRecipientService.updateTRecipientInfo(userRecipientInfo);
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }else{
                logger.info("银小二订单查询.." + resultObj);
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                cookieObj = new JSONObject();
                JSONObject loginReq = new JSONObject();
                String passport = userRecipientInfo.getChannelAccount().split("_")[0];
                loginReq.put("passport", passport);
                loginReq.put("password", MD5Util.stringMD5(accountObj.getString("password")));
                String loginStr = loginReq.toJSONString().toLowerCase();
                url = "https://longpay.xddshare.com/ysepay/auth/user/signin";
                String loginRes = HttpUtils.sendJsonMessage(url, headerMap, loginStr);
                //code
                JSONObject loginResObj = JSONObject.parseObject(loginRes);
                if (loginResObj.getIntValue("code") == 0) {
                    String qrcode = "https://longpay.xddshare.com/ysepay/h5/?tx=wz&qrcode=0x99qrcode#/pages/zfbPay/zfbPay?tx=wz&qrcode=0x99qrcode";
                    JSONObject tokenData = loginResObj.getJSONObject("data");
                    token = tokenData.getString("token");
                    cookieObj.put("token", token);
                    TRecipientInfo query = new TRecipientInfo();
                    //获取所有商户
                    url = "https://longpay.xddshare.com/ysepay/addmcht/api/ysemcht/list";
                    headerMap = new HashMap<>();
                    headerMap.put("cookie", "syPaySessionId=" + token);
                    headerMap.put("Longpay-Token", token);
                    headerMap.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/20) uni-app");
                    HttpResponse httpResponse = HttpUtils.httpFormGet(url, headerMap, "", "银小二");
                    String merListStr = httpResponse.getDocument().body().text();
                    JSONObject merListObj = JSONObject.parseObject(merListStr);
                    if (merListObj.getIntValue("code") == 0) {
                        JSONArray merList = merListObj.getJSONArray("data");
                        for (int i = 0; i < merList.size(); i++) {
                            JSONObject merObj = merList.getJSONObject(i);
                            if(merObj.getString("defCodeMask")==null){
                                continue;
                            }
                            cookieObj.put("qrcode", merObj.getString("defCodeMask"));
                            query = new TRecipientInfo();
                            query.setChannelAccount(passport + "_" + merObj.getString("userShortName"));
                            query.setChannel("alipay_yxe_h5");
                            List<TRecipientInfo> RecipientInfoList = userRecipientService.selectTRecipientInfoList(query);
                            if (RecipientInfoList.size() == 0) {
                                if (i == 0) {
                                    userRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("userShortName"));
                                    userRecipientInfo.setReceiptQrcode(qrcode.replaceAll("0x99qrcode", merObj.getString("defCodeMask")));
                                    userRecipientInfo.setOnline(1);
                                    userRecipientInfo.setCookie(cookieObj.toJSONString());
                                    userRecipientInfo.setProvince(merObj.getString("mercProv"));
                                    userRecipientInfo.setCity(merObj.getString("mercCity"));
                                    userRecipientService.updateTRecipientInfo(userRecipientInfo);
                                } else {
                                    TRecipientInfo newRecipientInfo = new TRecipientInfo();
                                    BeanUtils.copyProperties(userRecipientInfo, newRecipientInfo);
                                    newRecipientInfo.setId(null);
                                    newRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("userShortName"));
                                    newRecipientInfo.setReceiptQrcode(qrcode.replaceAll("0x99qrcode", merObj.getString("defCodeMask")));
                                    newRecipientInfo.setProvince(merObj.getString("mercProv"));
                                    newRecipientInfo.setCity(merObj.getString("mercCity"));
                                    newRecipientInfo.setOnline(1);
                                    newRecipientInfo.setCookie(cookieObj.toJSONString());
                                    userRecipientService.insertTRecipientInfo(newRecipientInfo);
                                }
                            } else {
                                TRecipientInfo recipientInfo1 = RecipientInfoList.get(0);
                                recipientInfo1.setOnline(1);
                                recipientInfo1.setCookie(cookieObj.toJSONString());
                                userRecipientService.updateTRecipientInfo(recipientInfo1);
                            }
                        }

                    } else {
//                        return new ErrorResponseData(-100, "登录失败");
                    }
                } else {
//                    return new ErrorResponseData(-100, "登录失败");
                }
            }
        }
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }




}
